package app.qrcode.browser.vacablarydemo.model.dao

import android.annotation.SuppressLint
import android.content.ContentValues
import android.util.Log
import app.qrcode.browser.vacablarydemo.MyApplication.Companion.context
import app.qrcode.browser.vacablarydemo.model.bean.VocabularyBean
import app.qrcode.browser.vacablarydemo.model.db.VocabularyDB

/**
 * Created by YiGo on 2022/4/19.
 */
object VocabularyDao {
    val dbHelper = VocabularyDB(context, VocabularyTab.TAB_NAME, 1)
    val db = dbHelper.writableDatabase


    fun add(engMeaning: String, chineseMeaning: String) {
        val values = ContentValues().apply {
            val word = engMeaning + "               "+chineseMeaning
            put(VocabularyTab.COL_WORD, word)
        }
        db.insert(VocabularyTab.TAB_NAME, null, values)
    }


    //删
    //初始化
    fun init(dataList: List<String>) {
        dataList.forEach {
            val values = ContentValues().apply {
                val word = it
                put(VocabularyTab.COL_WORD, word)
            }
            db.insert(VocabularyTab.TAB_NAME, null, values)
        }
    }
    //改

    //查
    @SuppressLint("Range")
    fun query(engMeaning: String, dataList: MutableList<VocabularyBean>) {
        dataList.clear()
        val cursor = db.rawQuery(
            "select * from ${VocabularyTab.TAB_NAME} where ${VocabularyTab.COL_WORD} like '%$engMeaning%'",
            null
        )
        if (cursor.moveToFirst()) {
            do {
                val id = cursor.getInt(cursor.getColumnIndex(VocabularyTab.COL_ID))
                val wordData = cursor.getString(cursor.getColumnIndex(VocabularyTab.COL_WORD))
                dataList.add(VocabularyBean(id, wordData))
            } while (cursor.moveToNext())
        }
        cursor.close()
    }

    @SuppressLint("Range")
    fun queryAll(dataList: MutableList<VocabularyBean>) {
        dataList.clear()
        val cursor = db.rawQuery("select * from ${VocabularyTab.TAB_NAME}", null)
        if (cursor.moveToFirst()) {
            do {
                val id = cursor.getInt(cursor.getColumnIndex(VocabularyTab.COL_ID))
                val wordData = cursor.getString(cursor.getColumnIndex(VocabularyTab.COL_WORD))
                dataList.add(VocabularyBean(id, wordData))
            } while (cursor.moveToNext())
        }
        cursor.close()
    }
}